package com.xli.sso.security.handler;

import com.xli.sso.security.exception.CustomerAuthenionException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        if (exception instanceof AccountExpiredException) {
            //账户过期，登录失败
        }
        else if (exception instanceof BadCredentialsException) {
            //用户名或密码错误，登录失败
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"用户名或密码错误\"}");
        }
        else if (exception instanceof CredentialsExpiredException) {
            //密码过期，登录失败
        }
        else if (exception instanceof DisabledException) {
            //账户被禁用，登录失败
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"您的账号已被禁用\"}");
        }
        else if (exception instanceof LockedException) {
            //账户被锁，登录失败
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"您的账号已被锁定\"}");
        }
        else if (exception instanceof InternalAuthenticationServiceException) {
            //账户不存在，登录失败
        }
        else if (exception instanceof CustomerAuthenionException) {
            //token验证失败
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"token验证失败\"}");
        }
        else {
            //其他登录失败
            response.getWriter().write("{\"code\":\"0\",\"msg\":\"用户获取失败\"}");
        }
    }
}
